﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace Omabar.CMS.Handler
{
    /// <summary>
    /// Captcha 的摘要说明
    /// </summary>
    public class Captcha : IHttpHandler, IRequiresSessionState
    {
        HttpContext context;
        //在此文件被访问时自动调用 相当于页面的PageLoad事件
        public void ProcessRequest(HttpContext context1)
        {
            this.context = context1;
            CreateCheckCodeImage(generateCheckCode());
        }

        #region 生成随机字符串
        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <returns></returns>
        private string generateCheckCode()
        {
            string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            char[] chastr = str.ToCharArray();
            string checkCode = "";
            Random rd = new Random();
            int i;
            for (i = 0; i < 4; i++)
            {
                checkCode += str.Substring(rd.Next(0, str.Length), 1);
            }

            //当生成好随机字符串后，将它保存在Session
            context.Session["Captcha"] = checkCode;
            return checkCode;
        }
        #endregion

        /// <summary>
        /// 根据字符串生成图片
        /// </summary>
        /// <param name="checkCode">字符串</param>
        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(80, 40);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 16, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                //准备缓存流
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                //将图片流存入缓存流
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                //清空相应对象内容
                context.Response.ClearContent();
                //设置相应对象内容格式为图片
                context.Response.ContentType = "image/jpeg";
                //将缓存流中的图片流返回客户端
                context.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();//销毁画板
                image.Dispose();//销毁图片
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}